
package cup.modules.system.service.impl;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cup.common.cache.RegionCache;
import cup.common.utils.GeneratorMapByList;
import cup.core.redis.cache.CupRedis;
import cup.modules.system.entity.Dept;
import cup.modules.system.entity.Region;
import cup.modules.system.excel.RegionExcel;
import cup.modules.system.service.IDeptService;
import cup.modules.system.vo.RegionVO;
import cup.core.log.exception.ServiceException;
import cup.core.tool.utils.BeanUtil;
import cup.core.tool.utils.Func;
import cup.core.tool.utils.StringPool;
import cup.modules.system.mapper.RegionMapper;
import cup.modules.system.service.IRegionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 行政区划表 服务实现类
 *
 * @author
 */
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements IRegionService {

	private final CupRedis cupRedis;
	private final IDeptService iDeptService;

	private static String RegionKey = "MyRegionInfo";

	@Autowired
	public RegionServiceImpl(CupRedis cupRedis,
							 IDeptService iDeptService) {
		this.cupRedis = cupRedis;
		this.iDeptService = iDeptService;
	}


	@Override
	public Map<String, Region> findCacheNameRegion() {
		String s = cupRedis.get(RegionKey);
		if (StringUtils.isNotBlank(s)) {
			List<Region> list = JSONUtil.toBean(s, new TypeReference<List<Region>>() {
			}, true);
			Map<String, Region> map = GeneratorMapByList.generator(() -> list, "name", String.class);
			return map;
		}
		List<Region> list = this.list(new QueryWrapper<Region>());

		Map<String, Region> map = GeneratorMapByList.generator(() -> list, "name", String.class);
		cupRedis.setEx(RegionKey, JSONUtil.toJsonStr(list), Duration.ofMinutes(30));

		return map;
	}

	@Override
	public Map<String, Region> findCacheCodeRegion() {
		String s = cupRedis.get(RegionKey);
		if (StringUtils.isNotBlank(s)) {
			List<Region> list = JSONUtil.toBean(s, new TypeReference<List<Region>>() {
			}, true);
			Map<String, Region> map = GeneratorMapByList.generator(() -> list, "code", String.class);
			return map;
		}
		List<Region> list = this.list(new QueryWrapper<Region>());

		Map<String, Region> map = GeneratorMapByList.generator(() -> list, "code", String.class);
		cupRedis.setEx(RegionKey, JSONUtil.toJsonStr(list), Duration.ofMinutes(30));

		return map;
	}

	@Override
	public Region findRegionByDeptId(String deptId) {
		Dept byId = iDeptService.getById(new Long(deptId));
		if (null == byId || StringUtils.isBlank(byId.getRegionId())) {
			return null;
		}
		Map<String, Region> cacheCodeRegion = findCacheCodeRegion();
		return cacheCodeRegion.get(byId.getRegionId());
	}

	@Override
	public boolean submit(Region region) {
		Integer cnt = baseMapper.selectCount(Wrappers.<Region>query().lambda().eq(Region::getCode, region.getCode()));
		if (cnt > 0) {
			return this.updateById(region);
		}
		// 设置祖区划编号
		Region parent = RegionCache.getByCode(region.getParentCode());
		if (Func.isNotEmpty(parent) || Func.isNotEmpty(parent.getCode())) {
			String ancestors = parent.getAncestors() + StringPool.COMMA + parent.getCode();
			region.setAncestors(ancestors);
		}
		// 设置省、市、区、镇、村
		Integer level = region.getRegionLevel();
		String code = region.getCode();
		String name = region.getName();
		if (level == RegionCache.PROVINCE_LEVEL) {
			region.setProvinceCode(code);
			region.setProvinceName(name);
		} else if (level == RegionCache.CITY_LEVEL) {
			region.setCityCode(code);
			region.setCityName(name);
		} else if (level == RegionCache.DISTRICT_LEVEL) {
			region.setDistrictCode(code);
			region.setDistrictName(name);
		} else if (level == RegionCache.TOWN_LEVEL) {
			region.setTownCode(code);
			region.setTownName(name);
		} else if (level == RegionCache.VILLAGE_LEVEL) {
			region.setVillageCode(code);
			region.setVillageName(name);
		}
		return this.save(region);
	}

	@Override
	public boolean removeRegion(String id) {
		Integer cnt = baseMapper.selectCount(Wrappers.<Region>query().lambda().eq(Region::getParentCode, id));
		if (cnt > 0) {
			throw new ServiceException("请先删除子节点!");
		}
		return removeById(id);
	}

	@Override
	public List<RegionVO> lazyList(String parentCode, Map<String, Object> param) {
		return baseMapper.lazyList(parentCode, param);
	}

	@Override
	public List<RegionVO> lazyTree(String parentCode, Map<String, Object> param) {
		return baseMapper.lazyTree(parentCode, param);
	}

	@Override
	public void importRegion(List<RegionExcel> data, Boolean isCovered) {
		List<Region> list = new ArrayList<>();
		data.forEach(regionExcel -> {
			Region region = BeanUtil.copy(regionExcel, Region.class);
			list.add(region);
		});
		if (isCovered) {
			this.saveOrUpdateBatch(list);
		} else {
			this.saveBatch(list);
		}
	}


}
